﻿using System;
using System.Net;
using System.Reflection;
using TencentWeiboSDK.Model;
using TencentWeiboSDK.Services.Util;

namespace TencentWeiboSDK.Deserializer
{
    /// <summary>
    /// 反序列化器管理器，根据数据类型返回用户所需要的反序列化器.
    /// </summary>
    public class DeserializerManager
    {
        private static DeserializerManager instance = new DeserializerManager();


        private DeserializerManager()
        { }

        /// <summary>
        /// 获取反序列化器管理器实例.
        /// </summary>
        public static DeserializerManager Instance
        {
            get {
                return instance;
            }
        }

        /// <summary>
        /// 构造微博(Status)对象的反序列化器.
        /// </summary>
        /// <returns>返回 StatusDeserializer 对象</returns>
        public BaseDeserializer BuildStatusDeserializer()
        {
            return BuildDeserializer("StatusDeserializer", null);
        }

        /// <summary>
        /// 构造用户(User)对象的反序列化器
        /// </summary>
        /// <returns>返回 UserDeserializer 对象</returns>
        public BaseDeserializer BuildUserDeserializer()
        {
            return BuildDeserializer("UserDeserializer", null);
        }

        /// <summary>
        /// 构造返回结果(Result)对象的反序列化器
        /// </summary>
        /// <returns>返回 UserDeserializer 对象</returns>
        public BaseDeserializer BuildResultDeserializer()
        {
            return BuildDeserializer("ResultDeserializer", null);
        }

        private BaseDeserializer BuildDeserializer(string serviceName, object[] parameters)
        {
            Type type = GetType(OAuthConfigruation.Format.ToString(), serviceName);

            if (null != type)
            {
                Type[] types = new Type[] { };

                if (null != parameters)
                {
                    types = new Type[] { parameters[0].GetType() };
                }

                ConstructorInfo conInfo = type.GetConstructor(types);
                return conInfo.Invoke(parameters) as BaseDeserializer;
            }
            
            return null;
        }

        private Type GetType(string format, string sericeName)
        {
            Type type = Type.GetType(string.Format("TencentWeiboSDK.Deserializer.{0}.{1}", format, sericeName));

            return type;
        }
    }
}
